package com.totyu.takamin.polling.testpolling;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "TestPolling";

//    /**
//     * 默认的时间间隔：1分钟
//     */
//    private static int DEFAULT_INTERVAL = 60 * 1000;
//    /**
//     * 异常情况下的轮询时间间隔:5秒
//     */
//    private static int ERROR_INTERVAL = 5 * 1000;
//    /**
//     * 当前轮询执行的时间间隔
//     */
//    private static int interval = DEFAULT_INTERVAL;
//    /**
//     * 轮询Handler的消息类型
//     */
//    private static int LOOP_WHAT = 10;
//    /**
//     * 是否是第一次拉取数据
//     */
//    private boolean isFirstRequest = false;
//    /**
//     * 第一次请求数据是否成功
//     */
//    private boolean isFirstRequestSuccess = false;
//
//    /**
//     * 开始执行轮询，正常情况下，每隔1分钟轮询拉取一次最新数据
//     * 在onStart时开启轮询
//     */
//    private void startLoop() {
//        L.i("页面onStart，需要开启轮询");
//        loopRequestHandler.sendEmptyMessageDelayed(LOOP_WHAT, interval);
//    }
//
//    /**
//     * 关闭轮询，在界面onStop时，停止轮询操作
//     */
//    private void stopLoop() {
//        L.i("页面已onStop，需要停止轮询");
//        loopRequestHandler.removeMessages(LOOP_WHAT);
//    }
//    /**
//     * 处理轮询的Handler
//     */
//    private Handler loopRequestHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//
//            // 如果首次请求失败，
//            if (!isFirstRequestSuccess) {
//                L.i("首次请求失败，需要将轮询时间设置为:" + ERROR_INTERVAL);
//                interval = ERROR_INTERVAL;
//            } else {
//                interval = DEFAULT_INTERVAL;
//            }
//
//            L.i("轮询中-----当前轮询间隔：" + interval);
//
//            loopRequestHandler.removeMessages(LOOP_WHAT);
//
//            // 首次请求为成功、或者定位未成功时执行重定位，并加载网点数据
//            if (!isFirstRequestSuccess) {
//                isClickLocationButton = false;
//                doLocationOption();
//            } else {
//                loadData();
//            }
//
//            System.gc();
//
//            loopRequestHandler.sendEmptyMessageDelayed(LOOP_WHAT, interval);
//
//        }
//    };


    /**
     * 图片地址集合
     */
    private String url[] = {
            "https://upload-images.jianshu.io/upload_images/5547112-e1891255ab773e5e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/658/format/webp",
            "https://upload-images.jianshu.io/upload_images/5547112-7185ea90b7d1c73a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/896/format/webp",
            "https://upload-images.jianshu.io/upload_images/5547112-b480383d58542aa8.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/896/format/webp",
            "https://upload-images.jianshu.io/upload_images/5547112-d6516a4bfdc39c75.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/896/format/webp",
            "https://upload-images.jianshu.io/upload_images/5547112-ebea20232bebf350.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/896/format/webp",
            "https://upload-images.jianshu.io/upload_images/5547112-3030a41f15a5e1ac.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/896/format/webp",
            "https://upload-images.jianshu.io/upload_images/5547112-914acbfbc1ddbb76.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/896/format/webp"
    };
    private ImageView imageView;
    private Handler mUIHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            handlerCount++;
            L.e("mUIHandler请求:" + msg.what);
            ImageModel model = (ImageModel) msg.obj;
            imageView.setImageBitmap(model.bitmap);
            childHandler.sendEmptyMessageDelayed(i, 2000);
        }
    };


    /**
     * {"status":1,"content":{"from":"en-EU","to":"zh-CN","out":"\u793a\u4f8b","vendor":"ciba","err_no":0}}
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        startLoop();


        imageView = (ImageView) findViewById(R.id.image);
        //创建异步HandlerThread
        handlerThread = new HandlerThread("downloadImage");
        //必须先开启线程
        handlerThread.start();
        //子线程Handler
        childHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                int idx = new Random().nextInt(6);
                childHandler.removeMessages(i);
                if (handlerCount > 10 && idx == 3) {
                    L.e("停止于:" + idx);
                    return false;
                }
                //在子线程中进行网络请求
                Bitmap bitmap = downloadUrlBitmap(url[idx]);
                ImageModel imageModel = new ImageModel();
                imageModel.bitmap = bitmap;
                L.e("图片:" + idx);
                imageModel.url = url[idx];
                Message msg1 = new Message();
                msg1.what = idx;
                msg1.obj = imageModel;
                //通知主线程去更新UI
                mUIHandler.sendMessage(msg1);
                return false;
            }
        });

//        for (int i = 0; i < 7; i++) {
        //每个1秒去更新图片
        childHandler.sendEmptyMessageDelayed(i, 2000);
//        }
    }

    int handlerCount = 0;
    final int i = 1;
    HandlerThread handlerThread;
    Handler childHandler;

    private Bitmap downloadUrlBitmap(String urlString) {
        HttpURLConnection urlConnection = null;
        BufferedInputStream in = null;
        Bitmap bitmap = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        stopLoop();
    }

}
